package com.git.contractmanagement.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.git.contractmanagement.config.BaseContext;
import com.git.contractmanagement.entity.Orders;
import com.git.contractmanagement.entity.User;
import com.git.contractmanagement.entity.dto.OrdersPageQueryDTO;
import com.git.contractmanagement.entity.dto.OrdersSubmitDTO;
import com.git.contractmanagement.entity.result.PageResult;
import com.git.contractmanagement.entity.vo.OrdersSubmitVO;
import com.git.contractmanagement.mapper.OrderMapper;
import com.git.contractmanagement.mapper.UserMapper;
import com.git.contractmanagement.service.OrderService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@Slf4j
public class OrderserviceImpl implements OrderService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public OrdersSubmitVO submitUserOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setCreatedTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orders.setCustomerId(BaseContext.getCurrentId());
        orderMapper.insertBatch(orders);

        OrdersSubmitVO orderSubmitVO = OrdersSubmitVO.builder()
                .id(orders.getId())
                .contractNo(orders.getContractNo())
                .status(orders.getStatus())
                .contractName(orders.getContractName())
                .createTime(orders.getCreatedTime())
                .customerId(orders.getCustomerId())
                .payAmount(orders.getPayAmount())
                .build();

        return orderSubmitVO;
    }

    @Override
    public Orders getOrder(Long orderId) {
        Orders orders = orderMapper.getOrder(orderId);
        return orders;
    }

    @Override
    public void cancelOrder(Long orderId) {
        Orders ordersDB = orderMapper.getOrder(orderId);
        if (ordersDB.getStatus().equals(Orders.PENDING_PAYMENT)) {
            Integer status = Orders.COMPLETED;
            orderMapper.updateStatus(status, orderId);
            return;
        }
        if (ordersDB.getStatus().equals(Orders.PAYMENT_MADE)) {
            //TODO 退款
            Integer status = Orders.CANCELLED;
            orderMapper.updateStatus(status, orderId);
            return;
        }
        throw new RuntimeException("订单状态异常");
    }

    /**
     * 用户订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */

    @Override
    public PageResult pageQueryUser(int pageNum, int pageSize, Integer status) {
        log.info("1用户ID：{}", BaseContext.getCurrentId());
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();

        // 关键修复：清除 PageHelper 残留的分页参数，避免 getById 被分页
        PageHelper.clearPage();
        User user = userMapper.selectById(BaseContext.getCurrentId());
        PageHelper.startPage(pageNum, pageSize);
        if (!user.getRole().equals(User.ROLE_ADMIN)) {
            ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        }

        // ordersPageQueryDTO.setUserId(1001l);
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page);
    }

    /**
     * 条件订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery4User(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 关键修复：清除 PageHelper 残留的分页参数，避免 getById 被分页
        PageHelper.clearPage();
        User user = userMapper.selectById(BaseContext.getCurrentId());

        if (!user.getRole().equals(User.ROLE_ADMIN)) {
            ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        }
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page);
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param
     */
    public void paySuccess(Long orderId) {


        // 根据订单号查询当前用户的订单
        // Orders ordersDB = orderMapper.getByNumberAndUserId(orderId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.PAYMENT_MADE)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    @Override
    public void complet(Long orderId) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getOrder(orderId);
        if (ordersDB.getStatus().equals(Orders.PAYMENT_MADE)) {
            Integer status = Orders.DELIVERY_IN_PROGRESS;
            orderMapper.updateStatus(status, orderId);
            return;
        }
        throw new RuntimeException("订单状态异常");
    }
}
